package cn.itsource.controller;

import cn.itsource.dto.OssDto;
import cn.itsource.result.JSONResult;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @Author: Jason
 * @Date: 2022/9/1 16:44
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private OssDto ossDto;

    @PostMapping("/fileUpload")
    public JSONResult fileUpload(@RequestParam("fileName") MultipartFile multipartFile){
        JSONResult returnVo = new JSONResult();
        ArrayList<String> strings = new ArrayList<>();
        strings.add("image/png");
        strings.add("image/gif");
        strings.add("image/jpeg");
        if (strings.contains(multipartFile.getContentType())){
            try {
                //获取文件名
                String fileName = multipartFile.getOriginalFilename();//123.jpg
                //获取文件类型
                String fileType = fileName.substring(fileName.lastIndexOf("."));//.jpg
                //uuid
                String uuid = UUID.randomUUID().toString().replace("-","");//hu23g4hj2gb423b4hj2b3hj4b32
                //company_logo/hu23g4hj2gb423b4hj2b3hj4b32.jpg
                String realName = "company_logo/" + uuid + fileType;
                OSS build = new OSSClientBuilder().build(ossDto.getEndpoint(), ossDto.getAccessKey(), ossDto.getSecretKey());
                PutObjectRequest putObjectRequest = new PutObjectRequest(ossDto.getBucketName(), realName, multipartFile.getInputStream());
                build.putObject(putObjectRequest);
                build.shutdown();//关闭OSSClient

                String imagePath = "https://" + ossDto.getBucketName()+"."+ossDto.getEndpoint()+"/"+realName;
                return returnVo.success(imagePath);
            } catch (IOException e) {
                //发生异常
                e.printStackTrace();
                return returnVo.error("文件上传发生异常了：" + e.getMessage());
            }
        }else {
            //文件格式错误，非jpg/png/gif
            return returnVo.error("文件格式不支持");
        }
    }
}
